package cn.nawang.ebeim.api.repository.impl;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;

/**
 * 
 * @ClassName: WarnMessageImpl
 * @Description: 获取预警消息
 * @author huanghj
 * @date 2015年10月27日 下午3:38:11
 * @version v1.0
 */
@Repository
public class WarnMessageImpl extends BaseQuery {
  @Autowired
  private EntityManagerFactory entityManagerFactory;

  public PageList findAllByPaging(Pages page) {
    StringBuffer sb = new StringBuffer();
    sb.append("select new cn.nawang.ebeim.api.bean.WarnMessBean");
    sb.append("(a.id,a.warnType,a.warnLevel,a.warnTime,a.warnPart,a.warnDesc,a.userId)");
    sb.append("from WarnMessage a where 1=1");
    String hqlCount = "select count(a.id) from  WarnMessage a where 1=1";
    String order = " order by a.id desc";
    PageList pl = null;
    try {
      String cod = joinSearchCondition(page);// 拼接查询条件
      pl = queryListByPaging(hqlCount + cod + order, sb.toString() + cod + order, page);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return pl;
  }

  public List<Map> getWarnList(String userId, String type, String level, String begin, String end) {
    StringBuffer sql = new StringBuffer(
        "select id,warn_type,warn_level,warn_time,warn_part,warn_desc from tb_warn_mess where user_id="
            + userId);
    if (!StringUtils.isEmpty(type)) {
      sql.append(" and warn_type=").append(type);
    }
    if (!StringUtils.isEmpty(level)) {
      sql.append(" and warn_level=").append(level);
    }
    if (!StringUtils.isEmpty(begin) && !StringUtils.isEmpty(end)) {
      sql.append(" and warn_time>").append(begin).append(" and warn_time<").append(end);
    }
    List<Map> objList = null;
    objList = find(sql.toString());
    if (objList != null && !objList.isEmpty()) {
      return objList;
    } else {
      return null;
    }

  }

  /**
   * 
   * @author lizh
   * @Description: sql查询公共接口
   * @param sql
   * @return List
   * @date 2015年10月14日下午6:09:41
   *
   * @修改人
   * @修改日期
   */
  public List find(String sql) {
    List<Map> objList = null;
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createNativeQuery(sql);
      query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
      objList = query.getResultList();
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return objList;
  }


}
